#!/usr/bin/python
# #! -*- coding:utf-8 -*-

import pymongo
import codecs,sys
from pymongo import MongoClient
import jieba
from gensim import corpora, models, similarities
import nltk
import jieba.analyse
from nltk.tokenize import word_tokenize
from pprint import pprint  # pretty-printer
from flask import Flask,request
import trainkick

reload(sys)
sys.setdefaultencoding('utf-8')
print "Flask server..."
app = Flask(__name__)
app.config.from_object(__name__)
#flatpages = FlatPages(app)

questid=''


@app.route('/queryill')
def index():
    questid=request.args.get("uuid",'')
    queryit(questid)
    return 'success'

kickpath="/root/python/"
conn = MongoClient("okzor.com",27017)
db = conn.health
db.authenticate("hou","hou@123")


dics=[]
dits={}
labels={}
count=1
mydoclist =[]
courses=[]
uuids=[]

content = db.kickchufang.find({'doctorId':'huanghuang'})
for i in content:
    line=str(i['desc'].encode("GB18030"))
    uuid=i['uuid']
    uuids.append(uuid)
    #print uuid,line
    courses.append(line)
courses_name = courses

#read uuids from file
fl = open(kickpath+'kick.uuids',"r")
info = fl.read()
fl.close()

#lib_texts =trainkick. pre_process_cn(courses)
dictionary = corpora.Dictionary.load(kickpath+'kick.dict')
print dictionary
lsi=models.LsiModel.load(kickpath+"kick.lsi")
indexes=similarities.MatrixSimilarity.load(kickpath+"kick.index")



def queryit(questionid):
    record = db.kickasking.find_one({'uuid': questionid})
    if (record):
        line = str(record['desc'].encode("GB18030"))
        print line
        questions = [line]
        target_courses = questions  # [u'石膏']
        # print "target_courses",target_courses
        target_text = trainkick.jieba_preprocess_cn(target_courses, low_freq_filter=False)


        ml_course = target_text[0]
        print "ml_course", ml_course

        ml_bow = dictionary.doc2bow(ml_course)
        print "ml_bow", ml_bow


        ml_lsi = lsi[ml_bow]  # ml_lsi 形式如 (topic_id, topic_value)
        sims = indexes[ml_lsi]


        sort_sims = sorted(enumerate(sims), key=lambda item: -item[1])


        print "sort_sims:",sort_sims[0:10]  # 看下前10个最相似的，第一个是基准数据自身
        print uuids[sort_sims[0][0]], sort_sims[0][1]
        print uuids[sort_sims[1][0]], sort_sims[1][1]
        print uuids[sort_sims[2][0]], sort_sims[2][1]
        doc=[]
        for i in range(0,3):
            if (float(sort_sims[i][1])>0.70):
                doc.append({"questid": questionid, "chufangid": uuids[sort_sims[i][0]], "score": float(sort_sims[i][1])})
        #doc = [{"questid": questionid, "chufangid": uuids[sort_sims[0][0]], "score": float(sort_sims[0][1])}]
        if (len(doc)>0):
            db.kickanswer.insert(doc)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)







